<?php
/*
 * @Author: 李明
 * @Date: 2021-08-10 17:44:54
 * @LastEditTime: 2022-01-22 11:28:14
 * @LastEditors: 李明
 * @Description:
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/admin/BranchController.php
 * @山东壹零贰肆信息科技有限公司
 */

namespace App\Http\Controllers\admin;

use App\Http\Controllers\BranchUtils;
use App\Http\Controllers\common\CommonFun;
use App\Http\Controllers\common\LMReturn;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Utils;
use App\Models\Branch;
use App\Models\WorkerBranch;
use App\Models\Worker;
use App\Models\WorkerBranchManage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\product\utils as productUtils;

use function GuzzleHttp\Promise\all;

class BranchController extends Controller
{
    /**
     * @description: 修改权重接口
     * @param {Request} $request
     * @return {*}
     */
    public function branchMove(Request $request)
    {
        try {
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            $all = $request->all();
            $dropType = $all['dropType']; // （三种状态）inner/里面，after/之后，before/之前
            $draggingNode = $all['draggingNode']; // 修改者的id
            $dropNode = $all['dropNode']; // 平级/下级  的id
            $move_branch = Branch::find($draggingNode);
            $stand_branch = Branch::find($dropNode);
        } catch (\Throwable $th) {
            return LMReturn::Error('传参出现问题', 'BC017');
        }
        try {
            switch ($dropType) {
                case 'before': // 增加权重
                    $weight = $stand_branch->weight + 512;
                    $weight = $this->dealWeight($weight, 1);
                    $move_branch->weight = $weight;
                    break;
                case 'inner': // 修改上级
                    $move_branch->pid = $stand_branch->id;
                    break;
                case 'after': //降低权重
                    $weight = $stand_branch->weight - 1;
                    $weight = $this->dealWeight($weight, 2);
                    $move_branch->weight = $weight;
                    break;
                default:
                    break;
            }
            $move_branch->save();
            return $move_branch;
        } catch (\Throwable $th) {
            return LMReturn::Error('处理参数出现问题', 'BC015');
        }
    }

    /**
     * @description:
     * @param double $weight 权重
     * @param {*} $type 增加是1     减少是2
     * @return double
     */
    public function dealWeight($weight, $type)
    {
        $count = count(Branch::where('weight', $weight)->get());
        if ($count > 0) {
            $weight = $type == 1 ? $weight - 1 : $weight + 1;
            return $this->dealWeight($weight, $type);
        } else {
            return $weight;
        }
    }

    //部门添加和修改
    public function BaseBmSave(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        //接收前端传递过来的值
        $all = $request->all();
        //判断是否传递了名称
        if (!isset($all['name'])) {
            return LMReturn::Error("参数不能为空");
        }
        //        if (isset($all['pid']) && $all['pid'] == 0) {
        //            unset($all['pid']);
        //        }
        try {
            //判断前端是否传递了部门的主键ID，如果没有传递，那么就添加，反之就是修改
            if (!array_key_exists("id", $all)) {
                DB::beginTransaction(); //开启事务
                //这里是添加
                $branchs = Branch::where('pid', $all['pid'])->where('is_effective', 1)->where('hid', null)->first();
                $branch = Branch::create($all);
                $branch->weight = $branch->id * 1024;
                $branch->is_effective = 1;
                $branch->save();
                $branch->product_classes()->sync(productUtils::get_branch_classify($all['pid']));
                if ($branchs) {
                    $branchs->hid = $branch->id;
                    $branchs->save();
                }
                DB::commit(); //提交至数据库
                return LMReturn::Success($branch, '添加成功');
            } else {
                //这里是修改
                if ($all['id'] == $all['pid']) {
                    return LMReturn::Error('无法设置自身为父级部门', 'BC014');
                }
                DB::beginTransaction(); //开启事务
                $branch = Branch::find($all['id']);
                if ($branch->pid != $all['pid']) {
                    $hbranch = Branch::where('hid', $all['id'])->first();
                    if ($hbranch) {
                        $hbranch->hid = $branch->hid;
                        $hbranch->save();
                    }
                    $pbranch = Branch::where('pid', $all['pid'])->where('is_effective', 1)->where('hid', null)->first();
                    if ($pbranch) {
                        $pbranch->hid = $all['id'];
                        $pbranch->save();
                    }
                }
                Branch::where("id", $all['id'])->update($all);
                DB::commit(); //提交至数据库
                return LMReturn::Success([], '修改成功');
            }
        } catch (\Throwable $th) {
            DB::rollBack();
            return LMReturn::Error('处理参数时发生错误', 'BC016');
        }
    }

    /**
     * @description: 修改父级部门
     * @param {Request} $request
     * @return {*}
     */
    public function branch_change_pid(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        //接收前端传递过来的值
        try {
            $all = $request->all();
            $branch_id = $all['branch_id'];
            $pid = $all['pid'];
        } catch (\Throwable $th) {
            return LMReturn::Error('请检查传参', 'BC011');
        }
        try {
            $branch = Branch::find($branch_id);
            $branch->pid = $pid;
            return LMReturn::Success($branch, '修改成功');
        } catch (\Throwable $th) {
            return LMReturn::Error('发生错误，请通知管理员BC012', 'BC012');
        }
    }

    /**
     * @description: 查询子部门
     * @param {*} $branch
     * @param {*} $branch_list
     * @param bool $is_all 是否所有，是所有（包含自身）  否只查询直系子部门
     */
    public static function get_branch_list($branch, $branch_list = [], $is_all = true)
    {
        if ($is_all) {
            $branch_list[] = $branch;
            $sum_branch_list = $branch->branches;
            foreach ($sum_branch_list as $branch) {
                $branch_list = BranchController::get_branch_list($branch, $branch_list);
            }
        } else {
            $branch_list = $branch->branches;
        }
        return $branch_list;
    }

    /**
     * @description: 根据传入的员工，查询所有子部门
     * @param {*} $worker
     * @param {*} $is_all 是否所有，是所有  否只查询 管理部门 的直系子部门
     */
    public static function worker_manage_branch_list($worker, $is_all = true)
    {
        $branchesManage = $worker->branchesManage;
        $branch_list = [];
        foreach ($branchesManage as $branch) {
            $branch_list = BranchController::get_branch_list($branch, $branch_list, $is_all);
        }
        return $branch_list;
    }

    /**
     * @description: 通过传入的员工id，查询他的所有管理部门（包含子部门）
     * @param {*} $worker_id
     * @return array $bmidList 所有的子部门的ID的一维数组
     */
    public static function queryBranchToWorkerID($worker_id, $branch_id = '0')
    {
        $branch_list = json_decode(Branch::get(), true);
        $branch_manage_list = WorkerBranchManage::where('worker_id', $worker_id)->get();
        $bmidList = [];
        foreach ($branch_manage_list as $manage_branch) {
            // 获取到所有的子集
            $bmidListSum = CommonFun::PidChildList($branch_list, $manage_branch->branch_id);
            // 转成数组
            $bmidListSum = explode(',', $bmidListSum);
            // 数组合并
            $bmidList = array_merge($bmidList, $bmidListSum);
        }
        // 查询特定部门的子部门
        if ($branch_id != '0') {
            if (in_array($branch_id, $bmidList)) { // 确认是否有管理该部门的权限
                $bmidList = CommonFun::PidChildList($branch_list, $branch_id);
                $bmidList = explode(',', $bmidList);
            } else {
                $bmidList = [];
            }
        }
        // 去除重复数据
        $bmidList = array_unique($bmidList);
        return $bmidList;
    }

    /**
     * @description: 通过传入的员工id，查询他的所有直系管理部门
     * @param {*} $worker_id
     * @return array $branch_list 所有的子部门的ID的一维数组
     */
    public static function querySmallBranchToWorkerID($worker_id, $branch_id = '0')
    {
        // 所有管理部门
        $branch_manage_list = WorkerBranchManage::where('worker_id', $worker_id)->get();
        $branch_list = [];
        // 获取他所有的管理直系部门
        foreach ($branch_manage_list as $manage_branch) {
            $where[] = ['pid', $manage_branch->branch_id];
            $list = Branch::where($where)->get();
            $branch_list = array_merge($branch_list, $list);
        }

        // 查询特定部门的子部门
        if ($branch_id != '0') { // 获取前端想要的  管理直系部门 ，必须是权限内的
            $branch = Branch::where('id', $branch_id)->first();
            if (in_array($branch, $branch_list)) { // 确认是否有管理该部门的权限
                $where[] = ['pid', $manage_branch->branch_id];
                $branch_list = Branch::where($where)->get();
            } else {
                $branch_list = [];
            }
        }

        return $branch_list;
    }

    /**
     * @description: 删除部门
     * @param {*}
     * @return {*}
     */
    public function deleteBranch(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        //接收前端传递过来的值
        try {
            $all = $request->all();
            $branch_id = $all['branch_id'];
        } catch (\Throwable $th) {
            return LMReturn::Error('接收参数发生错误', 'BC003');
        }
        try {
            $branch = Branch::find($branch_id);
            if ($branch) {
                $sum_branch_list = $branch->branches;
                if ($sum_branch_list) {
                    if (count($sum_branch_list) > 0) {
                        return LMReturn::Error('当前部门存在子部门', 'BC006');
                    }
                }
                $oa_models = $branch->oa_models;
                if (count($oa_models) > 0) {
                    return LMReturn::Error('当前部门存在审批模板', 'BC007');
                }
                $orders = $branch->orders;
                if (count($orders) > 0) {
                    return LMReturn::Error('当前部门存在订单', 'BC008');
                }
                $users = $branch->users;
                foreach ($users as $user) {
                    if ($user->user_status == 1) {
                        return LMReturn::Error('当前部门存在用户', 'BC010');
                    }
                }
                $workers = $branch->workers;
                foreach ($workers as $worker) {
                    if ($worker->user_status == 1 && $worker->account_status != 3) {
                        return LMReturn::Error('当前部门存在在职员工', 'BC010');
                    }
                }
                $hbranch = Branch::where('hid', $branch->id)->where('is_effective', 1)->first();
                if ($hbranch) {
                    $hbranch->hid = $branch->hid;
                    $hbranch->save();
                }
                $branch->pid = null;
                $branch->is_effective = 2;
                $branch->save();
                return LMReturn::Success([], '删除成功');
            } else {
                return LMReturn::Error('当前部门不存在', 'BC005');
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('处理参数发生错误', 'BC004');
        }
    }

    /**
     * @description: 查询部门详情
     * @param {Request} $request
     * @return {*}
     */
    public function queryBranchDetail(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        //接收前端传递过来的值
        $all = $request->all();

        if (isset($all['id'])) {
            $branch_id = $all['id'];
        } else {
            return LMReturn::Error('缺少必传参数', 'BC001');
        }

        try {
            $branch = Branch::where('id', $branch_id)->first();
        } catch (\Throwable $th) {
            return LMReturn::Error('数据发生错误', 'BC002');
        }
        return LMReturn::Success($branch);
    }


    // 查找部门有排序的树状图
    public function getBranchs(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $worker_id = $tokenInfo['worker_id'];
        $worker = Worker::find($worker_id);
        $manage_branchs = $worker->branchesManage;
        $branchs = Branch::where('is_effective', 1)->orderBy('branch.pid', 'asc')->get();
        $branchs_dics = [];
        $pid_list = [];
        foreach ($branchs as $branch) {
            $branch_dic = [];
            $branch_dic['id'] = $branch->id;
            $branch_dic['name'] = $branch->name;
            $branch_dic['branch_code'] = $branch->branch_code;
            $branch_dic['pid'] = $branch->pid;
            $branch_dic['hid'] = $branch->hid;
            $branch_dic['commission_rate'] = $branch->commission_rate;
            $branch_dic['task'] = $branch->task;
            $branch_dic['is_important'] = $branch->is_important;
            $branch_dic['remark'] = $branch->remark;
            $branch_dic['weight'] = $branch->weight;
            $branch_dic['create_time'] = $branch->create_time;
            $branch_dic['update_time'] = $branch->update_time;
            if (empty($branchs_dics[$branch->pid])) {
                $new_list = [];
                foreach ($pid_list as $pid_dic) {
                    if ($pid_dic['hid'] == null) {
                        $top_id = $pid_dic['id'];
                        $new_list[] = $pid_dic;
                        $last_pid = $pid_list[0]['pid'];
                        $branchs_dics[$last_pid] = Utils::getArrayHid($new_list, $pid_list, $top_id);
                        break;
                    }
                }
                $pid_list = [];
            }
            $pid_list[] = $branch_dic;
            $branchs_dics[$branch->pid] = $pid_list;
        }
        if (count($manage_branchs) > 0) {
            $worker_branch = $manage_branchs[0];
            $branch_dic = [];
            $branch_dic['id'] = $worker_branch->id;
            $branch_dic['name'] = $worker_branch->name;
            $branch_dic['branch_code'] = $worker_branch->branch_code;
            $branch_dic['pid'] = $worker_branch->pid;
            $branch_dic['hid'] = $worker_branch->hid;
            $branch_dic['commission_rate'] = $worker_branch->commission_rate;
            $branch_dic['task'] = $worker_branch->task;
            $branch_dic['is_important'] = $worker_branch->is_important;
            $branch_dic['remark'] = $worker_branch->remark;
            $branch_dic['weight'] = $worker_branch->weight;
            $branch_dic['create_time'] = $worker_branch->create_time;
            $branch_dic['update_time'] = $worker_branch->update_time;
            $branch_dic['treeList'] = Utils::getArrayBranch($branchs_dics, $worker_branch->id);
            return LMReturn::Success([$branch_dic]);
        } else {
            return LMReturn::Error('无权限');
        }
    }

    // 部门修改带顺序
    public function upBranch(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        if (empty($all['is_before'])) {
            return LMReturn::Error('未传入操作形式');
        }
        if (empty($all['opera_branch_id'])) {
            return LMReturn::Error('未传入需要操作的部门');
        }
        if (empty($all['refer_branch_id'])) {
            return LMReturn::Error('未传入需要参照的部门');
        }
        try {
            DB::beginTransaction(); //开启事务
            $opera_branch = Branch::find($all['opera_branch_id']);
            if ($opera_branch) {
                $opera_next_branch = Branch::where('hid', $all['opera_branch_id'])->first();
                if ($opera_next_branch) {
                    if ($opera_branch->hid == null) {
                        $opera_next_branch->hid = null;
                    } else {
                        $opera_next_branch->hid = $opera_branch->hid;
                    }
                    $opera_next_branch->save();
                }
            } else {
                return LMReturn::Error('没有该被修改的部门');
            }
            if ($all['is_before'] == 1) {
                // 传入1为在...之前（跟...的pid相同，hid两边都需要变化）
                $refer_branch = Branch::find($all['refer_branch_id']);
                if ($refer_branch) {
                    $opera_branch->hid = $refer_branch->hid;
                    $opera_branch->pid = $refer_branch->pid;
                    $opera_branch->save();
                    $refer_branch->hid = $all['opera_branch_id'];
                    $refer_branch->save();
                } else {
                    return LMReturn::Error('没有该被参照的部门');
                }
            } elseif ($all['is_before'] == 2) {
                // 传入2为在...之后（跟...的pid相同，hid两边都需要变化）
                $refer_branch = Branch::find($all['refer_branch_id']);
                if ($refer_branch) {
                    $refer_next_branch = Branch::where('hid', $all['refer_branch_id'])->first();
                    if (isset($refer_next_branch)) {
                        $refer_next_branch->hid = $all['opera_branch_id'];
                        $refer_next_branch->save();
                    }
                    $opera_branch->hid = $all['refer_branch_id'];
                    $opera_branch->pid = $refer_branch->pid;
                    $opera_branch->save();
                } else {
                    return LMReturn::Error('没有该被参照的部门');
                }
            } elseif ($all['is_before'] == 3) {
                // 传入3为在...里面，直接加到最前面
                $refer_branch = Branch::find($all['refer_branch_id']);
                if (isset($refer_branch)) {
                    $refer_p_branch = Branch::where('pid', $all['refer_branch_id'])->where('hid', null)->first();
                    if (isset($refer_p_branch)) {
                        $refer_p_branch->hid = $all['opera_branch_id'];
                        $refer_p_branch->save();
                    }
                    $opera_branch->pid = $all['refer_branch_id'];
                    $opera_branch->hid = null;
                    $opera_branch->save();
                } else {
                    return LMReturn::Error('没有该被参照的部门');
                }
            } else {
                return LMReturn::Error('未传入正确的操作方式');
            }
            DB::commit();
            return LMReturn::Success('修改成功');
        } catch (\Throwable $th) {
            DB::rollBack();
            return LMReturn::Error('处理参数时发生错误', 'BC016');
        }
    }
}
